package com.bysj.studentsystem.service.impl;

import com.bysj.studentsystem.util.RedisCacheUtil;
import com.bysj.studentsystem.dao.SysUserDao;
import com.bysj.studentsystem.domain.LoginUser;
import com.bysj.studentsystem.entity.SysUser;
import com.bysj.studentsystem.service.SysUserService;
import com.bysj.studentsystem.util.JwtUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * (SysUser)表服务实现类
 *
 * @author makejava
 * @since 2024-03-09 16:51:51
 */
@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {
    @Resource
    private SysUserDao sysUserDao;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Override
    public Map<String, Object> login(SysUser user) {
        // 进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        // 如果认证没通过，给出对应的提示
        if (Objects.isNull(authentication)){
            throw new RuntimeException("登录失败");
        }
        // 如果认证通过，使用userId生成一个jwt
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userId = loginUser.getSysUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        // 把完整的用户信息存入redis, userId作为key
        redisCacheUtil.setCacheObject("login:" + userId, loginUser);
        // 结果集
        Map<String, Object> map = new HashMap<>();
        map.put("token", jwt);
        map.put("userInfo", loginUser.getSysUser());
        return map;
    }

    @Override
    public boolean logout() {
        // 获取SecurityContextHolder中的用户信息
        UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authenticationToken.getPrincipal();
        Integer userId = loginUser.getSysUser().getId();
        // 删除redis中的用户信息
        redisCacheUtil.deleteObject("login:"+userId);
        return true;
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public SysUser queryById(Integer id) {
        return this.sysUserDao.queryById(id);
    }

    /**
     * 分页查询
     * @param sysUser 筛选条件
     * @param pageNum
     * @param pageSize
     * @return 查询结果
     */
    @Override
    public PageInfo queryByPage(SysUser sysUser, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysUser> list = this.sysUserDao.queryList(sysUser);
        return new PageInfo(list);
    }

    /**
     * 新增数据
     *
     * @param sysUser 实例对象
     * @return 实例对象
     */
    @Override
    public SysUser insert(SysUser sysUser) {
        sysUser.setCreateTime(new Date());
        sysUser.setCreateBy(userDetailsService.getCurrentUser().getId());
        this.sysUserDao.insert(sysUser);
        return sysUser;
    }

    /**
     * 修改数据
     *
     * @param sysUser 实例对象
     * @return 实例对象
     */
    @Override
    public SysUser update(SysUser sysUser) {
        // 获取之前的数据
        SysUser before = this.queryById(sysUser.getId());
        sysUser.setUpdateTime(new Date());
        sysUser.setPassword(before.getPassword());
        sysUser.setUpdateBy(userDetailsService.getCurrentUser().getId());
        this.sysUserDao.update(sysUser);
        return this.queryById(sysUser.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.sysUserDao.deleteById(id) > 0;
    }
}
